package com.paqCliente;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

import com.paqCliente.R;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.LinearLayout.LayoutParams;

public class cliente extends Activity {
	// implements ActionBar.TabListener {

	public static SectionsPagerAdapter mSectionsPagerAdapter;
	public static ViewPager mViewPager;
	public static plc_cliente miPlc;
	public static Context ctx;
	public static int pagina;
	public static Socket misocket;
	public static ObjectOutputStream out;
	public static ObjectInputStream in;
	public static int width;
	public static int height;
	public static String nombre_servidor;
	public static String pass_servidor;
	public static String dir_espejo;
	public static NotificationCompat.Builder mBuilder;
	public static ArrayList<LinearLayout> scrolls = new ArrayList<LinearLayout>();

	static boolean aplicacionInicializada = false;

	private static final int RESULT_SETTINGS = 1;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ctx = this;
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		SharedPreferences sharedPref = PreferenceManager
				.getDefaultSharedPreferences(this);

		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		width = size.x;
		height = size.y;
		// Set up the action bar.
		// final ActionBar actionBar = getActionBar();
		// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the activity.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						// actionBar.setSelectedNavigationItem(position);
					}
				});
		
		
//---------------------- notificacion de    alarmas ---------------------	
		
		
		Intent resultIntent = new Intent(this, panelAlarmas_cliente.class);
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		stackBuilder.addParentStack(panelAlarmas_cliente.class);
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.icono_cliente)
        .setContentTitle(getString(R.string.app_name))
        .setDefaults(Notification.DEFAULT_SOUND);
		mBuilder.setContentIntent(resultPendingIntent);

		nombre_servidor = sharedPref.getString("NOMBRE_SERVIDOR", "");
		pass_servidor = sharedPref.getString("PASS_SERVIDOR", "");
		dir_espejo = sharedPref.getString("DIR_ESPEJO", "");
		if (nombre_servidor.equals(""))
			nombre_servidor = "miservidor";
		if (pass_servidor.equals(""))
			pass_servidor = "abcd";
		if (dir_espejo.equals(""))
			dir_espejo = "82.223.78.55";
		
		if (!aplicacionInicializada) {
				Log.e("smain", "lanzo el thread");
				sock_cliente comunicacion = new sock_cliente();
				comunicacion.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);		
		}
		aplicacionInicializada = true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch (item.getItemId()) {
		case R.id.menu_settings:
			Intent i = new Intent(this, preferencias.class);
			startActivityForResult(i, RESULT_SETTINGS);
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/*
	 * @Override public void onTabSelected(ActionBar.Tab tab,
	 * FragmentTransaction fragmentTransaction) { // When the given tab is
	 * selected, switch to the corresponding page in // the ViewPager.
	 * mViewPager.setCurrentItem(tab.getPosition()); }
	 * 
	 * @Override public void onTabUnselected(ActionBar.Tab tab,
	 * FragmentTransaction fragmentTransaction) { }
	 * 
	 * @Override public void onTabReselected(ActionBar.Tab tab,
	 * FragmentTransaction fragmentTransaction) { }
	 */
	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a PlaceholderFragment (defined as a static inner class
			// below).
			return PlaceholderFragment.newInstance(position);
		}

		@Override
		public int getCount() {
			return servidor_cliente.plcs.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			plc_cliente p = servidor_cliente.plcs.get(position);
			return p.nombre;
		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static PlaceholderFragment newInstance(int sectionNumber) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
//			plc_cliente mp = servidor_cliente.plcs.get(sectionNumber);
//			LinearLayout milayout = dibuja_cliente.rellena(mp);
//			scrolls.add(milayout);
			return fragment;
		}

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			int section = getArguments().getInt(ARG_SECTION_NUMBER);

			View rootView = inflater.inflate(R.layout.comunicacion_item_detail,container, false);
			ScrollView miscroll = (ScrollView) rootView.findViewById(R.id.miscroll);
			miscroll.setScrollbarFadingEnabled(false);
			miscroll.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
			plc_cliente mp = servidor_cliente.plcs.get(section);
			LinearLayout milayout = dibuja_cliente.rellena(mp);
//			LinearLayout milayout = scrolls.get(section);
			if (milayout.getParent() != null)
				((ViewGroup) milayout.getParent()).removeView(milayout);
			miscroll.addView(milayout);
//			scrolls.add(milayout);



			return rootView;
		}
	}

}
